<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/5 0005
 * Time: 下午 3:03
 */

namespace App\Http\Classes;


use Illuminate\Support\Facades\DB;

class User
{
    private $tableName = 'users';
    private $tableDB = null;
    private $error = 0;
    private $message = array(
        0 => '修改密码失败',
        1 => '获取信息失败',
        3 => '邮箱注册失败',
        4 => '令牌过期',
        5 => '用户名与密码不匹配',
        6 => '旧密码不正确',
        7 => '修改信息失败',
        8 => '邮箱或密码错误'
    );

    public function __construct( $id = null )
    {
        $this->tableDB = DB::table( $this->tableName );

        if ( $id !== null )
        {
            $this->tableDB = $this->tableDB->where('id', '=', $id);
        }
    }

    public function tokenVerify( $token )
    {
        $result = $this->tableDB->where('token', '=', $token)->count();
        if ( $result == 1 )
        {
            return true;
        }
        else
        {
            $this->error = 4;
            return false;
        }
    }

    public function loginByCookie($token)
    {
        $result = $this->tableDB->where('token', '=', $token)->select(
            'id',
            'name',
            'head',
            'number',
            'phone',
            'email',
            'createtime',
            'token',
            'word_counting',
            'sentence_counting',
            'lesson_count',
            'time_count',
            'coins',
            'vip',
            'vip_endtime',
            'grade',
            'play_mod',
            'play_time',
            'sentence_mod',
            'plan_hours')->get();
        if ( $result )
        {
            $logs = DB::table('user_log')->where('user_id', '=', $result[0]->id)->get();

            $result[0]->head = HOST . $result[0]->head;

//            $result[0]->coins = isset($logs[0]->coins) ? $logs[0]->coins : 0;
            $result->coins = $result->time_count * $result->lesson_count - $result->coins;

            $result[0]->word_counting = isset($logs[0]->word_counted) ? (($result[0]->word_counting - $logs[0]->word_counted >= 0) ? ($result[0]->word_counting - $logs[0]->word_counted) : $result[0]->word_counting) : $result[0]->word_counting;

            $result[0]->sentence_counting = isset($logs[0]->sentence_counted) ? (($result[0]->sentence_counting - $logs[0]->sentence_counted >= 0) ? ($result[0]->sentence_counting - $logs[0]->sentence_counted) : $result[0]->sentence_counting) : $result[0]->sentence_counting;

            return $result[0];
        }
        else
        {
            $this->error = 4;
            return false;
        }
    }

    public function loginByEmail($email, $password)
    {
        $token = $this->createToken();
        $user = $this->tableDB->where('email', '=', $email)
            ->where('password', '=', hash('md5', $password));

        if ( $user->update(['token' => $token]) )
        {
            $result = $this->tableDB->where('token', '=', $token)->select(
                'id',
                'name',
                'head',
                'number',
                'phone',
                'email',
                'createtime',
                'token',
                'word_counting',
                'sentence_counting',
                'lesson_count',
                'time_count',
                'coins',
                'vip',
                'vip_endtime',
                'grade',
                'play_mod',
                'play_time',
                'sentence_mod',
                'plan_hours')->get()[0];

            $logs = DB::table('user_log')->where('user_id', '=', $result->id)->get();

            $result->head = HOST . $result->head;

//            $result->coins = isset($logs[0]->coins) ? $logs[0]->coins : 0;

            $result->coins = $result->time_count * $result->lesson_count - $result->coins;

            $result->word_counting = isset($logs[0]->word_counted) ? (($result->word_counting - $logs[0]->word_counted >= 0) ? ($result->word_counting - $logs[0]->word_counted) : $result->word_counting) : $result->word_counting;

            $result->sentence_counting = isset($logs[0]->sentence_counted) ? (($result->sentence_counting - $logs[0]->sentence_counted >= 0) ? ($result->sentence_counting - $logs[0]->sentence_counted) : $result->sentence_counting) : $result->sentence_counting;

            return $result;
        }
        else
        {
            $this->error = 5;
            return false;
        }
    }

    public function loginByPhone($phone, $password)
    {
        $token = $this->createToken();
        $user = $this->tableDB->where('phone', '=', $phone)
            ->where('password', '=', hash('md5', $password));
        if ( $user->update(['token' => $token]) )
        {
            $result = $this->tableDB->where('token', '=', $token)->select(
                'id',
                'name',
                'head',
                'number',
                'phone',
                'email',
                'createtime',
                'token',
                'word_counting',
                'sentence_counting',
                'lesson_count',
                'time_count',
                'coins',
                'vip',
                'vip_endtime',
                'grade',
                'play_mod',
                'play_time',
                'sentence_mod',
                'plan_hours')->get()[0];

            $logs = DB::table('user_log')->where('user_id', '=', $result->id)->get();

            $result->head = HOST . $result->head;

//            $result->coins = isset($logs[0]->coins) ? $logs[0]->coins : 0;
            $result->coins = $result->time_count * $result->lesson_count - $result->coins;

            $result->word_counting = isset($logs[0]->word_counted) ? (($result->word_counting - $logs[0]->word_counted >= 0) ? ($result->word_counting - $logs[0]->word_counted) : $result->word_counting) : $result->word_counting;

            $result->sentence_counting = isset($logs[0]->sentence_counted) ? (($result->sentence_counting - $logs[0]->sentence_counted >= 0) ? ($result->sentence_counting - $logs[0]->sentence_counted) : $result->sentence_counting) : $result->sentence_counting;

            return $result;
        }
        else
        {
            $this->error = 5;
            return false;
        }
    }

    public function loginByWeibo($weibo)
    {
        $token = $this->createToken();
        $user = $this->tableDB->where('weibo', '=', $weibo);
        if ( $user->update(['token' => $token]) )
        {
            $result = $this->tableDB->where('token', '=', $token)->select(
                'id',
                'name',
                'head',
                'number',
                'phone',
                'email',
                'createtime',
                'token',
                'word_counting',
                'sentence_counting',
                'lesson_count',
                'time_count',
                'coins',
                'vip',
                'vip_endtime',
                'grade',
                'play_mod',
                'play_time',
                'sentence_mod',
                'plan_hours')->get()[0];

            $logs = DB::table('user_log')->where('user_id', '=', $result->id)->get();

            $result->head = HOST . $result->head;

//            $result->coins = isset($logs[0]->coins) ? $logs[0]->coins : 0;
            $result->coins = $result->time_count * $result->lesson_count - $result->coins;

            $result->word_counting = isset($logs[0]->word_counted) ? (($result->word_counting - $logs[0]->word_counted >= 0) ? ($result->word_counting - $logs[0]->word_counted) : $result->word_counting) : $result->word_counting;

            $result->sentence_counting = isset($logs[0]->sentence_counted) ? (($result->sentence_counting - $logs[0]->sentence_counted >= 0) ? ($result->sentence_counting - $logs[0]->sentence_counted) : $result->sentence_counting) : $result->sentence_counting;

            return $result;
        }
        else
        {
            $this->error = 5;
            return false;
        }
    }

    public function getRecord($userId)
    {
        $user = $this->tableDB;

        $result = $user->where('id', $userId)->select(
            'lesson_count',
            'time_count',
            'coins',
                'id as ranking')->get();



        if ($result)
        {
            $result = $result[0];

            $number = DB::table( $this->tableName )->where('time_count', '>', $result->time_count)->count();

//            dd($number);

            $number = $number + 1;

            $result->coins = $result->time_count * $result->lesson_count - $result->coins;

            $result->ranking = $number;
            return $result;
        }
        else
        {
            $this->error = 1;
            return null;
        }
    }

    public function registerByEmail(array $data = null)
    {
        $dataArray = [];
        $dataArray['email'] = $data['email'];
        $dataArray['password'] = hash('md5', $data['password']);
        $dataArray['number'] = date('YmdHis');
        $result = $this->tableDB->insert($dataArray);
        if ( $result )
        {
            return true;
        }
        else
        {
            $this->error = 3;
            return false;
        }
    }

    public function registerByWeibo(array $data = null)
    {
        $dataArray = [];
        $dataArray['weibo'] = $data['weibo'];
        $dataArray['email'] = $data['email'];
        $dataArray['name'] = $data['name'];
        $dataArray['password'] = hash('md5', $data['password']);
        $dataArray['number'] = date('YmdHis');
        $result = $this->tableDB->insert($dataArray);
        if ( $result )
        {
            return true;
        }
        else
        {
            $this->error = 3;
            return false;
        }
    }

    public function registerByPhone(array $data = null)
    {
        $dataArray = [];
        $dataArray['phone'] = $data['phone'];
        $dataArray['password'] = hash('md5', $data['password']);
        $dataArray['number'] = date('YmdHis');
        $result = $this->tableDB->insert($dataArray);
        if ( $result )
        {
            return true;
        }
        else
        {
            $this->error = 3;
            return false;
        }
    }

    public function isEmailExists( $email )
    {
        $result = $this->tableDB->where('email', '=', $email)->count();
        if ( $result >= 1 )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public function isPhoneExists( $phone )
    {
        $result = $this->tableDB->where('phone', '=', $phone)->count();
        if ( $result >= 1 )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public function getIdByEmail( $email )
    {
        $result = $this->tableDB->where('email', '=', $email)->select('id')->get();
        if ( $result )
        {
            return $result[0]->id;
        }
        else
        {
            $this->error = 1;
            return null;
        }
    }

    public function updatePassword( $password = 123456 )
    {
        $result = $this->tableDB->update(['password' => hash('md5', $password)]);
        if ( $result )
        {
            return true;
        }
        else
        {
            $this->error = 0;
            return false;
        }
    }

    public function updatePasswordByPhone( $phone, $password = 123456 )
    {
        $result = $this->tableDB->where('phone', '=', $phone)->update(['password' => hash('md5', $password)]);
        if ( $result )
        {
            return true;
        }
        else
        {
            $this->error = 0;
            return false;
        }
    }

    public function isVip()
    {
        $vip = $this->vipRemove();
        //echo $vip;
        if ( $vip == 1 )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private function vipRemove()
    {
        $now = date('Y-m-d H:i:s');
        //echo $now;
        return $this->tableDB->where('vip_endtime', '<=', $now)->update(['vip' => 0]);
    }

    public function updatePasswordByOld( $oldpassword, $newpassword )
    {
        $result = $this->tableDB->where('password', '=', hash('md5', $oldpassword))->update(['password' => hash('md5', $newpassword)]);

        if ($result)
        {
            return true;
        }
        else
        {
            $this->error = 6;
            return false;
        }
    }

    public function updateName( $name )
    {
        $result = $this->tableDB->update(['name' => $name]);
        if ($result)
        {
            return true;
        }
        else
        {
            $this->error = 7;
            return false;
        }
    }

    public function increaseStudyTime( $minutes = 1 )
    {
        $result = $this->tableDB->increment('time_count', $minutes);

        if ( $result )
        {
            return true;
        }
        else
        {
            $this->error = 7;
            return false;
        }
    }

    public function updateHead( $path )
    {
        $result = $this->tableDB->update(['head' => $path]);

        if ( $result )
        {
            return true;
        }
        else
        {
            $this->error = 7;
            return false;
        }
    }

    public function increaseLessonCount()
    {
        $result = $this->tableDB->increment('lesson_count', 1);

        if ( $result )
        {
            return true;
        }
        else
        {
            $this->error = 7;
            return false;
        }
    }

    public function updateGrade($grade)
    {
        $result = $this->tableDB->update(['grade' => $grade]);

        if ( $result )
        {
            return true;
        }
        else
        {
            $this->error = 7;
            return false;
        }
    }

    public function updatePlayMod($playmod)
    {
        $result = $this->tableDB->update(['play_mod' => $playmod]);

        if ( $result )
        {
            return true;
        }
        else
        {
            $this->error = 7;
            return false;
        }
    }

    public function updatePlayTime($playtime)
    {
        $result = $this->tableDB->update(['play_time' => $playtime]);

        if ( $result )
        {
            return true;
        }
        else
        {
            $this->error = 7;
            return false;
        }
    }

    public function updateSentenceMod($sentencemod)
    {
        $result = $this->tableDB->update(['sentence_mod' => $sentencemod]);

        if ( $result )
        {
            return true;
        }
        else
        {
            $this->error = 7;
            return false;
        }
    }

    public function bindWeibo(array $data = null)
    {
        $result = $this->tableDB;

        $result = $result->where('email', $data['email'])
            ->where('password', hash('md5', $data['password']))
            ->update(['weibo' => $data['weibo']]);
        if ( $result === 1 )
        {
            $info = $this->loginByWeibo($data['weibo']);
            if ( $info )
            {
                return $info;
            }
            else
            {
                return false;
            }
        }
        else
        {
            $this->error = 8;
            return false;
        }
    }

    public function updatePlan(array $data = null)
    {
        $result = $this->tableDB;

        $result = $result->update($data);

        if ( $result )
        {
            return true;
        }
        else
        {
            $this->error = 7;
            return false;
        }
    }

    private function createToken()
    {
        $token = Common::getRand();
        return hash('md5', $token);
    }

    public function getMessage()
    {
        return $this->message[ $this->error ];
    }
}